package com.study.map.service.impl;

import com.alibaba.fastjson.JSON;
import com.study.map.config.GaodeMapConfig;
import com.study.map.constant.GaodeMapConstants;
import com.study.map.dto.WeatherRequest;
import com.study.map.dto.WeatherResponse;
import com.study.map.exception.MapServiceException;
import com.study.map.service.IWeatherService;
import com.study.map.util.MapHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 天气查询服务实现类
 *
 * @author study
 * @date 2025-08-31
 */
@Slf4j
@Service
public class WeatherServiceImpl implements IWeatherService {

    @Autowired
    private GaodeMapConfig gaodeMapConfig;

    @Autowired
    private MapHttpUtil mapHttpUtil;

    /**
     * 天气查询：根据城市查询天气信息
     *
     * @param request 天气查询请求参数
     * @return 天气查询结果
     * @throws MapServiceException 地图服务异常
     */
    @Override
    public WeatherResponse weather(WeatherRequest request) throws MapServiceException {
        try {
            // 构建请求URL
            String url = gaodeMapConfig.getApiUrl() + "/" + GaodeMapConstants.API_VERSION_V3 + GaodeMapConstants.WEATHER_URL;

            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.hasText(request.getCity())) {
                params.put("city", request.getCity());
            }
            params.put("extensions", request.getExtensions());
            params.put("output", request.getOutput());

            // 发送HTTP请求
            WeatherResponse response  = mapHttpUtil.doGet(url, params, WeatherResponse.class);

            // 解析响应结果
//            WeatherResponse response = JSON.parseObject(responseStr, WeatherResponse.class);

            // 检查响应状态
            if (!GaodeMapConstants.STATUS_SUCCESS.equals(response.getStatus())) {
                log.error("天气查询请求失败，状态码: {}, 信息: {}", response.getStatus(), response.getInfo());
                throw new MapServiceException("天气查询请求失败: " + response.getInfo());
            }

            return response;
        } catch (Exception e) {
            log.error("天气查询请求异常", e);
            throw new MapServiceException("天气查询请求异常", e);
        }
    }

    /**
     * 天气查询：根据城市查询天气信息
     *
     * @param city 城市名称或区域编码
     * @return 天气查询结果
     * @throws MapServiceException 地图服务异常
     */
    @Override
    public WeatherResponse weather(String city, Integer weatherType) throws MapServiceException {
        WeatherRequest request = new WeatherRequest();
        request.setCity(city);
        request.setExtensions(weatherType!=1?"all":"base");
        return weather(request);
    }
}